﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Amicus_Place_Finder.Language;
using Amicus_Place_Finder.Utils;
using Facebook;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Telerik.Windows.Controls;
using GestureEventArgs = System.Windows.Input.GestureEventArgs;

namespace Amicus_Place_Finder
{
    public partial class MainPage : PhoneApplicationPage
    {

        private bool fbFinished = false, ggFinished = false, fsFinished = false;

#region Page Constructor

        public MainPage()
        {
            InitializeComponent();
            BuildApplicationBar();
        }

        private async void PhoneApplicationPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            BusyIndicator.Visibility = Visibility.Visible;

            Shared.gps = new LocationService();
            await Shared.gps.WaitForChanges();
            Shared.gps.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(OnPositionChanged);
            OnPositionChanged(null, null);
            MapControl.SetView(Shared.gps.CurrentLocation, SettingUtils.Settings.ZoomLevel);
            GetNearBy();

            //(App.Current as App).rateReminder.Notify();
            if (SettingUtils.Settings.FirstTime)
            {
                MessageBox.Show(AppResources.Privacy);
                SettingUtils.Settings.FirstTime = false;
            }
        }

        private void BuildApplicationBar()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Opacity = 0.5;
            ApplicationBar.Mode = ApplicationBarMode.Minimized;

            var locateme = new ApplicationBarIconButton
                {
                    Text = AppResources.Me,
                    IconUri = new Uri("Assets/Appbar/appbar.locate.png", UriKind.Relative)
                };
            locateme.Click += new EventHandler(locateme_Click);
            ApplicationBar.Buttons.Add(locateme);

            var refresh = new ApplicationBarIconButton
            {
                Text = AppResources.Refresh,
                IconUri = new Uri("Assets/Appbar/appbar.sync.rest.png", UriKind.Relative)
            };
            refresh.Click += new EventHandler(refresh_Click);
            ApplicationBar.Buttons.Add(refresh);

            //var offline = new ApplicationBarMenuItem(AppResources.DownOffline);
            //offline.Click += new EventHandler(offline_Click);
            //ApplicationBar.MenuItems.Add(offline);

            var setting = new ApplicationBarMenuItem(AppResources.Settings);
            setting.Click += new EventHandler(setting_Click);
            ApplicationBar.MenuItems.Add(setting);


            var privacy = new ApplicationBarMenuItem(AppResources.PrivacyPolicy);
            privacy.Click += (ap, ep) =>
                {
                    MessageBox.Show("Your privacy is important to us. This application uses your current location to improve your mapping experience, detect where  you are. This may not be stored and shared. You may disable Location Services.");
                };
            ApplicationBar.MenuItems.Add(privacy);

            var likefb = new ApplicationBarMenuItem(AppResources.LikeUs);
            setting.Click += new EventHandler(likefb_Click);
            ApplicationBar.MenuItems.Add(likefb);
        }

#endregion

#region Search Function

        private async void GetNearBy()
        {
            try
            {
                fbFinished = ggFinished = fsFinished = false;
                BusyIndicator.Visibility = Visibility.Visible;

                Google1();
                Foursquare1();
                Facebook1();
            }
            catch
            {
                BusyIndicator.Visibility = Visibility.Collapsed;
                MessageBox.Show(AppResources.ConnectionError);
                //GetNearBy();
            }
        }

        private async void SearchPlaces(string text)
        {
            try
            {
                fbFinished = ggFinished = fsFinished = false;
                BusyIndicator.Visibility = Visibility.Visible;

                Google2();
                Foursquare2();
                Facebook2();
            }
            catch
            {
                BusyIndicator.Visibility = Visibility.Collapsed;
                MessageBox.Show(AppResources.ConnectionError);
            }
        }

        private void ShowDirection(PlaceItem item)
        {
            try
            {
                new BingMapsDirectionsTask
                {
                    Start = new LabeledMapLocation(AppResources.MyLocation, Shared.gps.CurrentLocation),
                    End = new LabeledMapLocation(item.Name, item.Location)
                }.Show();
            }
            catch { }
        }

        private void isFinished()
        {
            if (fbFinished == ggFinished == fsFinished == true)
            {
                BusyIndicator.Visibility = Visibility.Collapsed;
                MapControl.SetView(Shared.gps.CurrentLocation, SettingUtils.Settings.ZoomLevel);
            }
        }

#endregion

#region Control Event

        private void refresh_Click(object sender, EventArgs e)
        {
            if (tbSearch.Text != "")
                SearchPlaces(tbSearch.Text);
            else
                GetNearBy();
        }

        private void likefb_Click(object sender, EventArgs e)
        {
            (new WebBrowserTask { Uri = new Uri("http://www.facebook.com/TeamAmicus", UriKind.Absolute) }).Show();
        }

        private void setting_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/SettingPage.xaml", UriKind.Relative));
        }

        private void offline_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AppResources.ComingSoonText);
        }

        private void locateme_Click(object sender, EventArgs e)
        {
            if (SettingUtils.Settings.IsLocationServiceEnabled)
                MapControl.SetView(Shared.gps.CurrentLocation, SettingUtils.Settings.ZoomLevel);
            else
                MessageBox.Show(AppResources.EnableLocation);
        }

        void OnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            try
            {
                var lp = new List<PlaceItem>();
                lp.Add(new PlaceItem
                {
                    latitude = Shared.gps.CurrentLocation.Latitude,
                    longitude = Shared.gps.CurrentLocation.Longitude
                });
                UserLayer.ItemsSource = lp;
            }
            catch { }
        }

        private void tbSearch_ActionButtonTap(object sender, EventArgs e)
        {
            this.Focus();
            if (tbSearch.Text != "")
                SearchPlaces(tbSearch.Text);
            else
                GetNearBy();
        }

        private void tbSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
                tbSearch_ActionButtonTap(null, null);
        }

        private void ListPlaces_ItemTap(object sender, Telerik.Windows.Controls.ListBoxItemTapEventArgs e)
        {
            try
            {
                var item = ((RadDataBoundListBox)sender).SelectedItem as PlaceItem;
                ShowDirection(item);
            }
            catch { }
        }

        private void Grid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var s = sender as Grid;
            s.Background = new SolidColorBrush(Color.FromArgb(255, 173, 216, 230));
        }

        private void Grid_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var s = sender as Grid;
            s.Background = new SolidColorBrush(Colors.Transparent);
        }

        private void Grid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var s = sender as Grid;
            s.Background = new SolidColorBrush(Colors.Transparent);
        }

        private void GooglePushpin_OnTap(object sender, GestureEventArgs e)
        {
            try
            {
                var pp = sender as Pushpin;
                foreach (var item in (List<PlaceItem>)GoogleLayer.ItemsSource)
                {
                    if ((int) pp.Tag == item.ID)
                        ShowDirection(item);
                }
            }
            catch { }
        }

        private void FacebookPushpin_OnTap(object sender, GestureEventArgs e)
        {
            try
            {
                var pp = sender as Pushpin;
                foreach (var item in (List<PlaceItem>)FacebookLayer.ItemsSource)
                {
                    if ((int)pp.Tag == item.ID)
                        ShowDirection(item);
                }
            }
            catch { }
        }

        private void FoursquarePushpin_OnTap(object sender, GestureEventArgs e)
        {
            try
            {
                var pp = sender as Pushpin;
                foreach (var item in (List<PlaceItem>)FoursquareLayer.ItemsSource)
                {
                    if ((int)pp.Tag == item.ID)
                        ShowDirection(item);
                }
            }
            catch { }
        }

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            if (this.Orientation == PageOrientation.Landscape ||
                this.Orientation == PageOrientation.LandscapeLeft ||
                this.Orientation == PageOrientation.LandscapeRight)
            {
                MapPanel.Height = LayoutRoot.ActualHeight;
                tbSearch.Visibility = Visibility.Collapsed;
                ContentPanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                MapPanel.Height = 300;
                tbSearch.Visibility = Visibility.Visible;
                ContentPanel.Visibility = Visibility.Visible;
            }
            MapControl.SetView(Shared.gps.CurrentLocation, SettingUtils.Settings.ZoomLevel);
        }

#endregion

#region Async Place Search

        private async void Facebook1()
        {
            if (SettingUtils.Settings.IsFacebookPlaceEnable)
            {
                try
                {
                    FacebookLayer.ItemsSource = await FacebookAPI.GetNearbyPlaces(Shared.gps.CurrentLocation.Latitude, Shared.gps.CurrentLocation.Longitude);
                    ListPlacesFacebook.ItemsSource = FacebookLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            fbFinished = true;
            isFinished();
        }

        private async void Facebook2()
        {
            if (SettingUtils.Settings.IsFacebookPlaceEnable)
            {
                try
                {
                    FacebookLayer.ItemsSource =
                        await
                        FacebookAPI.GetNearbyPlacesByName(tbSearch.Text, Shared.gps.CurrentLocation.Latitude,
                                                          Shared.gps.CurrentLocation.Longitude);
                    ListPlacesFacebook.ItemsSource = FacebookLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            fbFinished = true;
            isFinished();
        }

        private async void Google1()
        {
            if (SettingUtils.Settings.IsGooglePlaceEnable)
            {
                try
                {
                    GoogleLayer.ItemsSource =
                        await
                        GoogleMapsService.SearchPlace("a", Shared.gps.CurrentLocation.Latitude,
                                                      Shared.gps.CurrentLocation.Longitude);
                    ListPlacesGoogle.ItemsSource = GoogleLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            ggFinished = true;
            isFinished();
        }

        private async void Google2()
        {
            if (SettingUtils.Settings.IsGooglePlaceEnable)
            {
                try
                {
                    GoogleLayer.ItemsSource =
                        await
                        GoogleMapsService.SearchPlace(tbSearch.Text, Shared.gps.CurrentLocation.Latitude,
                                                      Shared.gps.CurrentLocation.Longitude);
                    ListPlacesGoogle.ItemsSource = GoogleLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            ggFinished = true;
            isFinished();
        }

        private async void Foursquare1()
        {
            if (SettingUtils.Settings.IsFoursquarePlaceEnable)
            {
                try
                {
                    FoursquareLayer.ItemsSource =
                        await
                        FoursquareAPI.GetNearbyPlaces(Shared.gps.CurrentLocation.Latitude,
                                                      Shared.gps.CurrentLocation.Longitude);
                    ListPlacesFoursquare.ItemsSource = FoursquareLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            fsFinished = true;
            isFinished();
        }

        private async void Foursquare2()
        {
            if (SettingUtils.Settings.IsFoursquarePlaceEnable)
            {
                try
                {
                    FoursquareLayer.ItemsSource =
                        await
                        FoursquareAPI.GetPlaces(tbSearch.Text, Shared.gps.CurrentLocation.Latitude,
                                                Shared.gps.CurrentLocation.Longitude);
                    ListPlacesFoursquare.ItemsSource = FoursquareLayer.ItemsSource;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            fsFinished = true;
            isFinished();
        }

#endregion

    }
}